package com.example.culture.service.serviceimpl;
import com.example.culture.common.ServerResponse;
import com.example.culture.domain.*;
import com.example.culture.mapper.UserMapper;
import com.example.culture.service.UserService;
import com.example.culture.util.*;
import com.example.culture.util.redis.RedisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    public UserMapper userMapper;

    @Resource
    public RedisUtil redisUtil;

    private Logger logger= LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public User login(User user) {
        return userMapper.login(user);
    }

    @Override
    public List<Role> getRole() {
        return userMapper.getRole();
    }

    @Override
    public ServerResponse<String> register(User user) {
        //首先判断用户名是否存在
        User checkUsername=userMapper.checkUsername(user);
        if(ObjectUtils.isEmpty(checkUsername)){
            user.setCreateTime(new Date());
            User checkEmail=userMapper.checkEmail(user.getEmail());
            if(!ObjectUtils.isEmpty(checkEmail)){
                return ServerResponse.createByErrorMsg("该邮箱已经注册过了!");
            }
            String checkCode = (String) redisUtil.get("cultureemail_"+user.getEmail());
            if(StringUtils.isEmpty(checkCode)){
                return ServerResponse.createByErrorMsg("验证码已失效");
            }
            else if(!user.getCheckCode().equals(checkCode)){
                return ServerResponse.createByErrorMsg("验证码错误");
            }else{
                int i = userMapper.register(user);
                if (i != 0) {
                    redisUtil.del("cultureemail_"+user.getEmail());
                    return ServerResponse.createBySuccessMsg("注册成功");
                } else {
                    return ServerResponse.createByErrorMsg("注册失败");
                }
            }
        }else{
            return ServerResponse.createByErrorMsg("该登录名已存在");
        }
    }


    /**
     * 邮箱验证
     * @param email
     * @return
     */
    @Override
    public ServerResponse<String> generateCheckCode(String email) {
        synchronized (this){
            //邮箱非空验证
            if(email==null||"".equals(email)){
                return ServerResponse.createByErrorMsg("邮箱不能为空,请填入有效地址");
            }
            //生成随机的6位数字验证码
            String verificationCode= SmsRandomCodeUtil.generateRandomSixNum();
            //调用邮箱发送
            AliyunMailUtil.sendMail(email,"浙江师范大学跨文化交际项目用户注册","您的验证码为："+verificationCode+"。此验证码三分钟内有效，请及时注册。"+"<br><br>"+"本邮件是系统自动发送的，请勿直接回复！感谢您的注册，祝您使用愉快！");
            redisUtil.set("cultureemail_"+email,verificationCode,180);
            // todo 发送的验证码拼接了之前的验证码？？ 获取content内容时候出现getContent现象
            // todo 2019年8月28日09:23:18 接口中屏蔽验证码
            return ServerResponse.createBySuccessMsg("发送验证码成功");
        }
    }

    /**
     * 忘记密码时候，根据邮箱返回验证码
     * @param email
     * @return
     */
    @Override
    public ServerResponse<String> forgetSendEmailCode(String email) {
        //验证邮箱是否存在
        User resultCount = userMapper.checkEmail(email);
        if(ObjectUtils.isEmpty(resultCount)){
            return ServerResponse.createByErrorMsg("邮箱不存在！");
        }
        //生成随机的验证码
        String verificationCode= SmsRandomCodeUtil.generateRandomSixNum();
        //调用邮箱发送
        AliyunMailUtil.sendMail(email,"浙江师范大学跨文化交际项目用户重置密码","您的验证码为："+verificationCode+"。此验证码五分钟内有效，请及时重置密码。"+"<br><br>"+"本邮件是系统自动发送的，请勿直接回复！");
        //发送成功保存邮箱地址对应的验证码 todo 5分钟 已解决
        redisUtil.set("cultureforget_"+email,verificationCode,300);
        return ServerResponse.createBySuccessMsg("验证码已经发送");
    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> updatePassword(User user) {
        String checkCode = (String) redisUtil.get("cultureforget_"+user.getEmail());
        int updatePasswordResult=0;
        if (StringUtils.isEmpty(checkCode)) {
            return ServerResponse.createByErrorMsg("验证码已经失效");
        } else {
            if (!checkCode.equals(user.getCheckCode())) {
                return ServerResponse.createByErrorMsg("验证码输入错误");
            } else {
                User checkEmailUser = userMapper.checkEmail(user.getEmail());//通过邮箱来查询该用户信息
                if (!ObjectUtils.isEmpty(checkEmailUser)) {
                    updatePasswordResult = userMapper.updatePassword(user);//新旧密码替换
                }
            }
        }
        if (updatePasswordResult != 0) {
            redisUtil.del("cultureforget_"+user.getEmail());
            return ServerResponse.createBySuccessMsg("修改成功");
        } else {
            return ServerResponse.createByErrorMsg("修改失败");
        }
    }


    @Override
    public void expertLogin(User expertLoginUser) {
        userMapper.expertLogin(expertLoginUser);
    }


    @Override
    public ServerResponse<StatisticsData> accountUser() {
        StatisticsData statisticsData=new StatisticsData();
        int count = userMapper.selectUserCounts();//用户总数量（教师+高校学生+管理员+评审专家）
        int visitors= (int) redisUtil.get("visited");//总访问人数
        statisticsData.setCount(count);
        statisticsData.setVisitors(visitors);
        return ServerResponse.createBySuccess(statisticsData);
    }

    @Override
    public ServerResponse roleNums() {
        List<Nums> numsList=userMapper.getNums();//获取角色信息
        List<Nums> roleNums=new ArrayList<>();//角色数据处理
        for (int i = 0; i < numsList.size(); i++) {
            Nums nums=new Nums();
            if("1".equals(numsList.get(i).getName())){
                nums.setName("管理员");
            }else if("2".equals(numsList.get(i).getName())){
                nums.setName("教师");
            }else if("3".equals(numsList.get(i).getName())){
                nums.setName("学生");
            }else if("4".equals(numsList.get(i).getName())){
                nums.setName("评审专家");
            }
            nums.setValue(numsList.get(i).getValue());
            roleNums.add(nums);
        }
        return ServerResponse.createBySuccess(roleNums);
    }

    @Override
    public ServerResponse<PageInfo> searchUser(Integer pageNum, Integer pageSize, String username,String school,String classesName,Integer roleId) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfo> userList = userMapper.searchUser(username,school,classesName,roleId);
        PageInfo pageInfo = new PageInfo(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    @Transactional
    @Override
    public ServerResponse deleteUser(Integer id) {
        int deleteStatus = userMapper.deleteUser(id);//通过编号来删除该用户
        if (deleteStatus != 0) {
            return ServerResponse.createBySuccessMsg("成功删除该学生");
        } else {
            return ServerResponse.createByErrorMsg("删除该学生失败");
        }
    }


    @Override
    public ServerResponse searchClassesAndGroup(String classesName,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Classes> classes=userMapper.searchClassesAndGroup(classesName);//获取班级以及分组级联信息
        return ServerResponse.createBySuccess(classes);
    }

    @Override
    public ServerResponse getClassesAndGroup() {
        List<Classes> classes=userMapper.getClassesAndGroup();//获取班级以及分组级联信息
        return ServerResponse.createBySuccess(classes);
    }


    @Override
    public ServerResponse<String> insertBackUser(User user) {
        user.setCreateTime(new Date());
        User checkUsername=userMapper.checkUsername(user);
        if(ObjectUtils.isEmpty(checkUsername)){
            User checkEmail=userMapper.checkEmail(user.getEmail());
            if(!ObjectUtils.isEmpty(checkEmail)){
                return ServerResponse.createByErrorMsg("该邮箱已经注册过了!");
            }
            int checkInsertBackUser=userMapper.register(user);//添加新用户
            if(checkInsertBackUser!=0){
                return ServerResponse.createBySuccessMsg("成功添加用户");
            }else{
                return ServerResponse.createByErrorMsg("添加用户失败");
            }
        }else{
            return ServerResponse.createByErrorMsg("该登录名已存在");
        }
    }

    @Override
    public ServerResponse<String> updateUser(User user) {
//        User checkUpdateUser = userMapper.checkUpdateUser(user);//通过用户编号来查询该用户信息
        int checkLoginName=userMapper.checkLoginName(user.getLoginName(),user.getId());
        int checkEmail=userMapper.checkUserEmail(user.getEmail(),user.getId());
        if(checkLoginName==1){
//            logger.info("修改用户名：#{},原有用户名：#{}",user.getLoginName(),checkUpdateUser.getLoginName());
            return ServerResponse.createByErrorMsg("该登录名已存在");
        }else if(checkEmail==1){
            return ServerResponse.createByErrorMsg("该邮箱已存在");
        }else{
            int checkUpdateStatus=userMapper.updateUser(user);//修改用户信息
            if(checkUpdateStatus!=0){
                return ServerResponse.createBySuccessMsg("成功修改该用户信息");
            }else{
                return ServerResponse.createByErrorMsg("修改该用户信息失败");
            }
        }
    }

    @Override
    public ServerResponse addExperiment(Experiment experiment) {
        int checkAddExperimentStatus=userMapper.addExperiment(experiment);
        if(checkAddExperimentStatus!=0){
            return ServerResponse.createBySuccessMsg("成功提交实验信息");
        }else{
            return ServerResponse.createByErrorMsg("提交实验信息失败");
        }
    }

    @Override
    public ServerResponse getExperiment(Integer pageNum, Integer pageSize, String school, String classesName, String groupName, String username) {
        PageHelper.startPage(pageNum,pageSize);
        List<Experiment> experimentList=userMapper.getExperiment(school,classesName,groupName,username);
        return ServerResponse.createBySuccess(experimentList);
    }
}
